package com.maimao.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author MaoLin Wang
 * @date 2021/4/25 下午3:49
 */
@Configuration
public class ThreadPoolConfig {

    public static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;
    public static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 2;
    public static final int QUEUE_CAPACITY = CORE_POOL_SIZE * 10;
    public static final int KEEP_ALIVE_SECONDS = 30_000;
    public static final int AWAIT_TERMINATION_SECONDS = 60;

    /**
     * 修改密码、找回密码、绑定邮箱时使用
     */
    @Bean
    public ThreadPoolTaskExecutor userEmailSendPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(CORE_POOL_SIZE);
        //最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        //队列容量
        executor.setQueueCapacity(QUEUE_CAPACITY);
        //活跃时间
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        //线程名字前缀
        executor.setThreadNamePrefix("userSafeCenter-emailSend-");

        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 调度器shutdown被调用时等待当前被调度的任务完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(AWAIT_TERMINATION_SECONDS);
        executor.initialize();
        return executor;
    }
}
